package org.game;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

public class IOManager {
	private static HashMap<String,File> fileMap = new HashMap<String,File>();
	/**Get a specific file by name
	 * 
	 * @param resource the name of the file to get
	 * @return the specified file
	 */
	public static File getFile(String resource){
		if(fileMap.containsKey(resource)){
			return fileMap.get(resource); 
		}
		File res = new File(resource);
		fileMap.put(res.getName(), res);
		return res;
	}
	/**Add a specific file to the File Map
	 * 
	 * @param resource the location of a file to add to the File Map
	 * @return
	 */
	public static String include(String resource){
		if(fileMap.containsValue(new File(resource))){
			return new File(resource).getName();
		}
		File in = new File(resource);
		fileMap.put(in.getName(), in);
		return in.getName();
	}
	/**
	 * 
	 * @param file the file to add to the File Map
	 * @return the key for the file
	 */
	public static String include(File file){
		if(fileMap.containsValue(file)){
			return file.getName();
		}
		fileMap.put(file.getName(), file);
		return file.getName();
	}
	/** Get and split the lines of a file
	 * into an organized String array.
	 * 
	 * @param resource the location of the file
	 * @param regex what to split the file's lines by.
	 * @return An Array of the lines of a file
	 */
	public static String[] getFileContents(String resource,String regex){
		File file;
		if(fileMap.containsKey(resource)){
			file = fileMap.get(resource);
		}else{
			file = new File(resource);
		}
		StringBuilder string = new StringBuilder();
		try{
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String line;
			while((line = reader.readLine()) != null){
				string.append(line);
			}
		}catch(IOException e){
			e.printStackTrace();
			System.err.println("Could not read file:"+resource);
			return null;
		}
		String[] values = string.toString().split(regex);
		return values; 
	}
	/**
	 * Output the entire file map's contents.
	 */
	public static void outputMap(){
		System.out.println("IOManager Output:");
		for(String key : fileMap.keySet()){
			System.out.println(key+","+fileMap.get(key));
		}
		System.out.println("End of IOManager Output;");
	}
	/** Check if the file map has a specific file
	 * 
	 * @param file the file to check for
	 * @return if the file is contained in the file map
	 */
	public static boolean has(File file){
		return fileMap.containsKey(file.getName());
	}
	/**Check if a file exists
	 * 
	 * @param path the path of the file
	 * @return if the file exists
	 */
	public static boolean exists(String path){
		return new File(path).exists();
	}
}
